<?php

namespace app\admin\service;


use app\common\model\integral\IntegralProductSpec;
use app\common\model\integral\IntegralProductSpecValue;
use think\facade\Db;

class IntegralProductSpecService extends BaseService
{

    public function __construct()
    {
        $this->model = new IntegralProductSpec();
    }


    public function edit()
    {
        $data = request()->param();
        $list = getter($data, 'spec_value_list', []);
        if (empty($list)) {
            return message('规格值不能为空！', false);
        }

        $rowId = $this->model->edit($data);
        if ($rowId) {
            IntegralProductSpecValue::specValueUpdate($list,$rowId);
            return message();
        }
        return message('错误', false);
    }



    public function getList()
    {
        $map = [];
        $title = getter(request()->param(), 'title', '');
        !empty($title) && $map[] = ['title', '=', $title];
        $list = $this->model->where($map)->page(PAGE, PERPAGE)->select();

        foreach ($list as $k =>$v) {
           $list[$k]['spec_value_list'] = IntegralProductSpecValue::where('spec_id', $v['id'])->field('id, title')->select()->toArray();
           $list[$k]['spec_value_name'] = IntegralProductSpecValue::where('spec_id', $v['id'])->field('group_concat(title) as title')->find()->toArray()['title'];
        }

        //获取数据总数
        $count = $this->model->where($map)->count();

        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );
        return $message;
    }


    public function getProductSpecList(){
        $list = $this->model->where('status', 1)->field('id,title')->select()->toArray();

        if (count($list) > 0){
            $ls = [];
            foreach ($list as $i => $v) {
                $ls[] = array(
                    'id' => $v['id'],
                    'title' => $v['title']
                );
            }
            return message('操作成功', true, $ls);
        }
        return message('请先创建商品规格！', false);
    }

}